/**
 * 
 */
package com.db.stockexchange.server;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;

import com.db.stockexchange.common.messages.FIXMessage;
import com.db.stockexchange.server.connection.ConnectionListener;
import com.db.stockexchange.server.connection.ConnectionPool;

/**
 * @author Rayman
 * Runs server application
 */
public class ServerApp {
	private static final String KEY_PORT = "port";
	private static final String CMD_CLOSE = "close";

	/**
	 * @param args
	 * arg1 - port number
	 * @throws FileNotFoundException
	 * @throws IOException 
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		ConnectionListener listener;
		
		LinkedBlockingQueue<FIXMessage> fromEngine = new LinkedBlockingQueue<FIXMessage>();
		LinkedBlockingQueue<FIXMessage> toEngine = new LinkedBlockingQueue<FIXMessage>();
		
		Properties properties = new Properties();
		properties.load(new FileInputStream("server.properties"));
		
		StockExchangeEngine engine = new StockExchangeEngine(new MessageHandler(fromEngine, toEngine), properties);
		try {
			int port = Integer.parseInt(properties.getProperty(KEY_PORT));
			listener = new ConnectionListener(port, new ConnectionPool(toEngine, fromEngine));
			new Thread(listener, "ConnectionListener").start();
		} catch (IOException e) {
			System.out.println("Exception occurred while creating connection listener: " + e.getMessage());
			return;
		}
		
		// expect close command
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String s;
		while (true) {
			try {
				s = reader.readLine();
				if (s.equalsIgnoreCase(CMD_CLOSE))
					break;
			} catch (IOException e) {
				System.out.println("Exception occurred while reading from console: " + e.getMessage());
			}
		}
		
		listener.close();
		engine.close();
	}
}
